<?php

/**
 * 带有status，created_date,last_modified_date字段的sql组装函数
 * @param array $arr
 * @param int $status
 * @param string $table
 * @param string $type 默认是insert
 * @return	string $sql	返回组装好的sql语句
 */
function makeSql($arr, $status=0, $table,$type='insert')
{
	$str1 = ''; $str2 = '';
	foreach($arr as $k=>$v)
	{
		$str1 .= "`{$k}`,";
		if($k == 'status')		//status为整形字段不能加引号
		{
			$str2 .= "{$v},";
		}
		else 
		{
			$str2 .= "'{$v}',";
		}
	}
	
	$sql  = "{$type}  INTO `{$table}` (" . $str1 . " status, created_date,last_modified_date ) VALUES (" . $str2 . " $status, NOW(),NOW())";
	return $sql;
}

/**
 * 检查访问权限，用单服与央服通信时验证
 */
function checkToken(){
	global $api_key;
	$mkey = @$_REQUEST['mkey'];
	$time = @$_REQUEST['time'];
	$ckey = md5($time.$api_key);
	if($mkey != $ckey)
	{
		exit('deny access!');
	}
}

/**
 * 获取当前正常开服的服务器，平台列表
 */
function getServerInfo()
{
	global $db;
	$sql = "SELECT s.id AS server_id,s.server as server_name,s.platform_id,p.`name` as platform_name,s.innerip1
			FROM tb_server AS s
			LEFT JOIN tb_platform AS p ON p.id = s.platform_id
			WHERE s.`status` = 1;";
	$servers = $db->getAll($sql);
	return $servers;
}

/**
 * 获取当前平台列表
 * @return 平台列表数组id,name
 */
function getPlatforms()
{
	global $db;
	$sql = "SELECT id,name FROM tb_platform";
	$platforms = $db->getAll($sql);
	return $platforms;
}

/**
 * 根据server_id转换成erver_name
 * @param $server_id
 * @param $isString true:$server_id为一个字符串;false:$server_id为一个数组;
 */
function explainServerName($server_id,$isString=true)
{
	if(empty($server_id)) return;
	if($isString)
	{
		$server_id = explode('|', $server_id);
	}
	global $db;
	$nameString = array();
	foreach($server_id as $k=>$v)
	{
		$sql = "select server from tb_server where id = $v";
		$nameString[] = $db->getOne($sql);
	}
	return implode('|', $nameString);
}


/**
 * 获取当前正常开服的服务器列表
 * @return 正在运行的服务器列表数组
 */
function getServers($platform_id = 0)
{
	if(!empty($platform_id))
	{
		$where = ' and platform_id = '.$platform_id;
	}
	else
	{
		$where = '';
	}
	
	global $db;
	$sql = "SELECT id,platform_id,`server`,innerip1 FROM tb_server WHERE `status` in (0,1)".$where;
	$servers = $db->getAll($sql);
	return $servers;
}


/**
* 记录PHP的log
* @param string $file_name 文件名。默认保存在html目录上一级的php-tmp/Y-m-d/中，可指定二级目录
* @param string $str log内容
*/
function logError($file_name, $str){
	$file_name = trim($file_name, '/');
	$date = date('Y-m-d');
	$time = date('Y-m-d H:i:s');
	$str = $time . "\t" . $str;
	$path = dirname(dirname(ROOT_PATH)) . "/php-tmp/{$date}";
	checkPath($path);
	$file = $path . "/" . $file_name;
	error_log($str, 3, $file);
}

/**
* 生成数据到指定目录文件
* @param string $file_path 目的目录
* @param string $file_name 文件名
* @param string $data 数据
*/
function generateData($file_path, $file_name, $data){
	$file_path = rtrim($file_path, '/');
	checkPath($file_path);
	$fp = fopen($file_path . '/' . $file_name, 'a+');
	$flat = fwrite($fp, $data);
	fclose($fp);
	if ($flat == FALSE) {
		$errmsg = "generate txt data fail\n"
		. "file:{$file_path}/{$file_name}\n"
		. "data:{$data}\n\n";
		logError("generate_data/{$file_name}", $errmsg);
	}
}

/**
* 检查目录是否存在和可写，不存在则创建
* @param string $path
*/
function checkPath($path){
	if (file_exists($path) === FALSE) {
		if (mkdir($path, 0777, TRUE) === FALSE)
		die("{$path}文件夹建立失败");
	}
	if (is_writable($path) === FALSE){
		die("{$path}文件夹不可写");
	}
}

/**
 * 检查文件是否存在和可写，不存在则创建
 * @param string $path
 */
function checkFile($filename){
	if (file_exists($filename) === FALSE){
		if (fopen($filename, 'w+') === FALSE)
		die("{$filename}文件建立失败");
	}
	if (is_writable($filename) === FALSE){
		die("{$filename}文件不可写");
	}
}

/**
 * 获得所有服务器信息
 * @return array(id=>name)
 */
function getAllServer(){
	global $db;
	$sql = "SELECT id, server FROM tb_server";
	$query = $db->query($sql);
	$server_enum = array(0 => '全部');
	while ($row = $db->fetch_array($query)){
		$server_enum[$row['id']] = $row['server'];
	}
	return $server_enum;
}

/**
 * 执行一个HTTP请求
 * @param string $url 请求URL
 * @param array $params 请求的参数
 * @param string $method 请求方法
 * @param int $timeout 执行的超时时间
 * @return string HTTP返回信息
 */
function makeRequest($url, $params, $method = 'POST', $timeout = 60){
	global $api_key;
	$time = time();
	$mkey = md5($time . $api_key);
	$params['time'] = $time;
	$params['mkey'] = $mkey;
	$ch = curl_init();
	$opt = array();
	$opt[CURLOPT_HEADER] = FALSE;
	$opt[CURLOPT_RETURNTRANSFER] = TRUE;
	$opt[CURLOPT_TIMEOUT] = $timeout;
	if ($method == 'POST'){
		$opt[CURLOPT_POST] = TRUE;
		$opt[CURLOPT_POSTFIELDS] = $params;
		$opt[CURLOPT_URL] = $url;
	}else{
		$queryList = http_build_query($params, null, '&');
		$opt[CURLOPT_URL] = $url . '?' . $queryList;
	}
	curl_setopt_array($ch, $opt);
	$contents = curl_exec($ch);
	//$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);
	//if ($return_code == 200) return $contents;
	//else return NULL;
	return $contents;
}

/**
 * 根据单页记录数获取总页数
 * @param int $pagetotal 总记录数
 * @param int $pagesize 单页记录数
 * @return number 总页数
 */
function getPageNumber($pagetotal, $pagesize){
	return ceil($pagetotal / $pagesize);
}

/**
 * 去除字符窜中的空格和换行
 * @param string $str	要操作的字符串
 * @return string
 */
function clear($str) {
	$str = str_replace(' ', '', $str);
	$str = str_replace("\r", '', $str);
	$str = str_replace("\n", '', $str);
	$str = str_replace("\t", '', $str);
	return $str;
}

/**
 * 转换要导出的字符串编码为GB2312
 * @param string $str
 * @return string
 */
function t($str='')
{
	return iconv('UTF-8','GBK',$str);
}

/**
 * 统计相差天数
 * @param Datetime $date1
 * @param Datetime $date2
 * @return number
 */
function days($date1,$date2)
{
	$temp = strtotime($date1)-strtotime($date2);
	$days = round($temp/(60*60*24), 0);
	return $days;
}


/**
 * 返回有数据的统计时间区间
 * @param $begin  开始时间
 * @param $end	   结束时间
 * @param $intval 统计间隔时间
 */
function stat_date($s_date,$e_date,$intval)
{
	$today = date('Y-m-d', time());
	$begin = $s_date;
	while(!($e_date < $s_date) )
	{
		$stat_date = date('Y-m-d',strtotime("$intval days",strtotime($s_date)));
		
		if(($stat_date > $today))
		{
			break;
		}
		$finish = isset($s_date) ? $s_date : null;				//有统计数据的截止日期
		
		$s_date = date('Y-m-d',strtotime('1 days',strtotime($s_date)));
	};
	
	return array($begin,$finish);
}


/**
 * 解释装备附加属性
 * @param Int $value 对应的data值
 * @return string
 */
function explain_equip_attr($value){
	global $rs_equip_attr_enum;
	$attr_id = $value >> 16;
	$attr_value = $value - ($attr_id << 16);
	if ($attr_id >= 0x80){
		//0x80开头的是增加百分比,其他为增加值
		$attr_id = $attr_id - 0x80;
		return $rs_equip_attr_enum[$attr_id] . '+' . $attr_value . '%';
	}else return $rs_equip_attr_enum[$attr_id] . '+' . $attr_value;
}

/**
 * 解释镶嵌宝石附加属性
 * @param Int $item_id 宝石ID
 * @return NULL|string
 */
function explain_equip_gem_attr($item_id){
	if (!$item_id) return NULL;
	if ($item_id - 0x4100 <= 10) $gem_effect = '力量';		//力量宝石
	elseif ($item_id - 0x4110 <= 10) $gem_effect = '智力';	//智力宝石
	elseif ($item_id - 0x4120 <= 10) $gem_effect = '体质';	//体质宝石
	elseif ($item_id - 0x4130 <= 10) $gem_effect = '精神';	//精神宝石
	elseif ($item_id - 0x4140 <= 10) $gem_effect = '敏捷';	//敏捷宝石
	elseif ($item_id - 0x4150 <= 10) $gem_effect = '物攻';	//物攻宝石
	elseif ($item_id - 0x4160 <= 10) $gem_effect = '魔攻';	//魔攻宝石
	elseif ($item_id - 0x4170 <= 10) $gem_effect = '生命';	//生命宝石
	elseif ($item_id - 0x4180 <= 10) $gem_effect = '物防';	//物防宝石
	elseif ($item_id - 0x4190 <= 10) $gem_effect = '魔防';	//魔防宝石
	elseif ($item_id - 0x41A0 <= 10) $gem_effect = '暴击';	//暴击宝石
	elseif ($item_id - 0x41B0 <= 10) $gem_effect = '命中';	//命中宝石
	elseif ($item_id - 0x41C0 <= 10) $gem_effect = '闪避';	//闪避宝石
	$gem_level = $item_id % 16 + 1;							//宝石等级
	if ($item_id >= 0x4100 && $item_id <= 0x414F){
		//力量、智力、体质、精神、敏捷
		if ($gem_level <= 6) $gem_attr = $gem_level * 5;
		elseif ($gem_level == 7 ) $gem_attr = 40;
		elseif ($gem_level == 8 ) $gem_attr = 50;
		elseif ($gem_level == 9 ) $gem_attr = 75;
		elseif ($gem_level == 10 ) $gem_attr = 100;
	}elseif (($item_id >= 0x4150 && $item_id <= 0x416F) || ($item_id >= 0x4180 && $item_id <= 0x419F)){
		//物攻、魔攻、物防、魔防
		if ($gem_level <= 6) $gem_attr = $gem_level * 15;
		elseif ($gem_level == 7) $gem_attr = 120;
		elseif ($gem_level == 8) $gem_attr = 150;
		elseif ($gem_level == 9) $gem_attr = 225;
		elseif ($gem_level == 10) $gem_attr = 300;
	}elseif ($item_id >= 0x4170 && $item_id <= 0x417F){
		//生命
		if ($gem_level <= 6) $gem_attr = $gem_level * 75;
		elseif ($gem_level == 7) $gem_attr = 600;
		elseif ($gem_level == 8) $gem_attr = 750;
		elseif ($gem_level == 9) $gem_attr = 1125;
		elseif ($gem_level == 10) $gem_attr = 1500;
	}elseif ($item_id >= 0x41A0 && $item_id <= 0x41BF){
		//暴击、命中
		if ($gem_level <= 6) $gem_attr = $gem_level * 3;
		elseif ($gem_level == 7) $gem_attr = 25;
		elseif ($gem_level == 8) $gem_attr = 35;
		elseif ($gem_level == 9) $gem_attr = 50;
		elseif ($gem_level == 10) $gem_attr = 70;
	}elseif ($item_id >= 0x41C0 && $item_id <= 0x41CF){
		//闪避
		if ($gem_level <= 6) $gem_attr = $gem_level * 4;
		elseif ($gem_level == 7) $gem_attr = 30;
		elseif ($gem_level == 8) $gem_attr = 40;
		elseif ($gem_level == 9) $gem_attr = 60;
		elseif ($gem_level == 10) $gem_attr = 80;
	}
	return $gem_effect . '+' . $gem_attr;
}

/**
 * 加密函数
 * @param Boolean $Is_Des_Encrypt 是否DES加密 0:否，1:是
 * @param String $action action值
 * @param String $username 用户名
 * @param Int $timestamp 时间戳
 * @param String $key 密钥
 * @return String
 */
function encrypt($Is_Des_Encrypt, $action, $username, $timestamp ,$key){
	if ($Is_Des_Encrypt){
		$cipher = MCRYPT_DES;																//密码类型
		$modes = MCRYPT_MODE_ECB;															//密码模式
		$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher,$modes),MCRYPT_RAND);				//初始化向量
		$str = $username.$timestamp;
		$str_encrypt = md5($action.mcrypt_encrypt($cipher,$key,$str,$modes,$iv));			//加密函数
	}else{
		$str_encrypt = md5($action.$key.$username.$timestamp);
	}
	return $str_encrypt;
}

//JS跳转页面
function gourl($iAlert,$iPage,$history='',$target="window")
{
	if ($iAlert != "") {
		echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		echo '<script language="javascript">alert("'.$iAlert.'")</script>';
	}
	if ($iPage != "") {
		echo '<script language="javascript">'.$target.'.location.href = "'.$iPage.'";</script>';
		exit;
	}
	if ($history != "") {
		echo '<script language="javascript">history.go('.$history.');</script>';
		exit;
	}
}

/*
 列表分页显示函数
 **参数
 $page:当前页
 $pagesize:每页记录条数
 $count:总记录条数
 $url：页面地址
 Return:String
 */
function showpage($page,$pagesize,$count,$url)
{
	if ($page == "") {
		$page = 1;
	}
	if($count == 0) {
		$pagestr="<font color='red'>没有搜索到合乎的记录！</font>";
		return $pagestr;
	}
	$pagenum = ceil($count / $pagesize);
	$pagestr="总计<font color=\"#FF0000\">".$count."</font>记录&nbsp;&nbsp;第<font color=\"#FF0000\">$page</font>/".$pagenum."页&nbsp;&nbsp;";
	if($page==1)
	{
		$pagestr.="首页&nbsp;&nbsp;上一页&nbsp;&nbsp;";
	}
	else
	{
		$pagestr.="<a href=\"".$url."\">首页</a>&nbsp;&nbsp;<a href=\"".$url."page=".($page-1)."\">上一页</a>&nbsp;&nbsp;";
	}
	if($page<$pagenum)
	{
		$pagestr.="<a href=\"".$url."page=".($page+1)."\">下一页</a>&nbsp;&nbsp;<a href=\"".$url."page=".$pagenum."\">尾页</a>";
	}
	else
	{
		$pagestr.="下一页&nbsp;&nbsp;尾页";
	}
	$pagestr.="&nbsp;&nbsp;<select name=\"pageno\" id=\"pageno\" onchange=\"window.location.href='".$url."page='+this.value\">";
	for($i=1;$i<=$pagenum;$i++)
	{
		$pagestr.="<option value=\"$i\" ";
		if ($page == $i)
		{
			$pagestr .= "selected=\"selected\"";
		}
		$pagestr .= ">$i</option>";
	}
	$pagestr.="</select>";
	return $pagestr;
}

/*
 禁止表单外部提交
 */
function chkfrompath()
{
	global $db;
	$path = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
	$frompath = strtolower(@$_SERVER['HTTP_REFERER']);
	preg_match("/\/\/(.*)\/system/",$path,$arr_path);
	preg_match("/\/\/(.*)\/system/",$frompath,$arr_frompath);
	if($arr_path[1]!=$arr_frompath[1])
	{
		$db->close();//关闭数据库
		gourl('对不起，来路不明。','/logout.php','','top');
	}
}


/*
 验证权限
 @$mname 所属菜单名称
 return null
 */
function chkpurview($mname)
{
	global $db;
	$sql = "select a.group_id,b.group_name from tb_ad_adminuser as a left join tb_ad_admingroup as b on a.group_id =b.id where a.id='".$_SESSION['UserId']."'";
	if (!$row = $db->getRow($sql)) {
		$db->close();
		gourl('','/zwcenter/noqx.html');
	}
	if ($row['group_name'] != 'administrator') {
		//$sql = "select b.id from tb_ad_purview as a left join tb_ad_resource as b on b.id=a.resource_id where b.label='".$label."'";
		$sql = "select b.id from tb_ad_purview as a join tb_ad_menu as b on b.id=a.resource_id && a.group_id='".$row['group_id']."' and b.name='".$mname."'";
		//echo $sql;exit;
		if (!$db->getRow($sql)) {
			$db->close();
			gourl('','/zwcenter/noqx.html');
		}
	}
}

/**
 * 
 * 递归转义变量中特殊字符
 * @param $value
 */
function addslashes_deep($value)
{
	if(empty($value))
	{
		return $value;
	}
	else 
	{
		return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
	}
}

/*
 新验证权限
 return null
 */
function chkpermission()
{
	global $db;
	$thisurl = str_replace('/admin/' ,'' ,$_SERVER['SCRIPT_NAME']);
	if(@$_SESSION['UserId']=="" || @$_SESSION['UserGroup']=="") {
		gourl("","admin_login.php",'',"top");
	}
	else if($_SESSION['UserGroup']!="1" && $thisurl!='top.php' && $thisurl!='left.php' && $thisurl!='right.php' && $thisurl!='logout.php') {
		$sql =	"SELECT COUNT(*) AS permission FROM tb_ad_purview p ".
				"JOIN tb_ad_menu m ON m.id = p.resource_id ".
				"WHERE p.group_id = {$_SESSION['UserGroup']} AND m.url LIKE '{$thisurl}%'";
		$permission = $db->getRow($sql);
		$sql =	"SELECT COUNT(*) AS inpermission FROM tb_ad_menu ".
				"WHERE url LIKE '{$thisurl}%'";
		$inpermission = $db->getRow($sql);
		if(!$permission['permission'] && $inpermission['inpermission']) {
			gourl('你无此权限','',-1);
		}
	}
}

/**
 * 根据不同协议组合通用头部协议信息
 * @param array $action
 * @return array:
 */
function merge_header($action){
	global $magic,$version,$serialno,$p_type,$checksum,$flag;
	return array_merge($magic,$version,$serialno,$p_type[$action],$checksum,$flag);
}

/**
 * 解包头部协议的长度
 * @param Int $size
 * @return string
 */
function unpack_header_format(){
	//return 'H40commonheader/';
	return 'H8magic/H2version/H8serialno/H8type/H8checksum/H4flag/H2size_flag/';
}

/**
 * 获取操作者IP
 * @return String
 */
function get_ip(){
	if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	}elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	}else{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return $ip ? $ip : 'unknow IP';
}

/**
 * 保存管理员操作记录
 * @param Int $oper_type
 * @param String $oper_value
 * @param Int $oper_status
 * @return boolean
 */
function save_adminoper($oper_type, $oper_value, $oper_status){
	global $db;
	$time = date('Y-m-d H:i:s', time());
	$ip = get_ip();
	$oper_status  = hexdec($oper_status);
	$oper_value = htmlspecialchars($oper_value);
	$sql = "INSERT INTO tb_ad_adminoper_hist (id, admin_id, oper_type, oper_value, oper_date, oper_status,
	status, created_date, last_modified_date, oper_ip) VALUES (null, '{$_SESSION['UserId']}', '{$oper_type}', '{$oper_value}',
	'{$time}', {$oper_status}, 1, '{$time}', '{$time}', '{$ip}')";
	return $db->query($sql);
}

//PHP正则表达式提取超链接
function match_links($content) 
{
	$match = array();
	$match['link'] = '';
	$match['content'] = '';
	$links = array();
	@preg_match_all("'<\s*a\s.*?href\s*=\s*([\"\'])?(?(1)(.*?)\\1|([^\s\>]+))[^>]*>?(.*?)</a>'isx",$content,$links);
	while(@list($key,$val) = each($links[2])) 
	{
		if(!empty($val))
		$match['link'][] = $val;
	}
	while(@list($key,$val) = each($links[3])) 
	{
		if(!empty($val))
		$match['link'][] = $val;
	}
	while(@list($key,$val) = each($links[4])) 
	{
		if(!empty($val))
		$match['content'][] = $val;
	}
	while(@list($key,$val) = each($links[0])) 
	{
		if(!empty($val))
		$match['all'][] = $val;
	}
	
	return $match;
}

/**
 * 检查某个目录是否存在，不存在则建立此目录
 * @param $folder
 */
function make_dir($folder)
{
	$reval = false;
	
	if(!file_exists($folder))
	{
		@umask(0);
		preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
		
		$base = ($atmp[0][0] == '/') ? '/' : '';
		
		foreach($atmp[1] as $val)
		{
			if('' != $val)
			{
				$base .= $val;
				if('..' == $val || '.' == $val)
				{
					$base .= '/';
					continue;
				}
			}
			else 
			{
				continue;
			}
			
			$base .= '/';
			
			if(!file_exists($base))
			{
				if(@mkdir(rtrim($base,'/'),0777))
				{
					@chmod($base, 0777);
					$reval = true;
				}
			}
		}
	}
	else 
	{
		$reval = is_dir($folder);
	}
	
	clearstatcache();
	return $reval;
}


?>
